#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // 初始化互斥锁
int shared_counter = 0; // 共享变量

// 定义一个结构体，用于传递多个参数
typedef struct {
    int thread_id; // 线程编号
    int additional_data; // 其他数据
} ThreadArgs;

void* do_work(void* arg) {
    ThreadArgs* args = (ThreadArgs*)arg; // 将 void* 转换为 ThreadArgs*
    int thread_id = args->thread_id;
    int additional_data = args->additional_data;
    free(arg); // 释放动态分配的内存

    for (int i = 0; i < 5; i++) { // 每个线程循环5次
        pthread_mutex_lock(&lock);
        // 修改共享变量
        shared_counter++;
        printf("Thread %d is working. Shared counter: %d, Additional data: %d\n", 
               thread_id, shared_counter, additional_data);
        pthread_mutex_unlock(&lock);
    }
    return NULL;
}

int main() {
    pthread_t tid1, tid2;

    // 为线程1传递参数
    ThreadArgs* arg1 = malloc(sizeof(ThreadArgs));
    arg1->thread_id = 1;
    arg1->additional_data = 100; // 示例附加数据
    pthread_create(&tid1, NULL, do_work, arg1);

    // 为线程2传递参数
    ThreadArgs* arg2 = malloc(sizeof(ThreadArgs));
    arg2->thread_id = 2;
    arg2->additional_data = 200; // 示例附加数据
    pthread_create(&tid2, NULL, do_work, arg2);

    // 等待线程结束
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    pthread_mutex_destroy(&lock); // 销毁互斥锁
    printf("Final shared counter: %d\n", shared_counter);
    return 0;
}
